package com.qtu.redis_service.controller;

import com.qtu.redis_service.service.RedisService;
import com.qtu.util.CacheUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("api/redis")
public class RedisController {

    @Autowired
    private RedisService redisService;

    /**
     * 存储缓存数据
     */
    @ResponseBody
    @RequestMapping(value = "set")
    public String set(@RequestParam("key") String key, @RequestBody Object value){
        try {
            Object obj = CacheUtil.linkedHashMapToObject(value, value.getClass());
            redisService.set(key, obj);
            return "ok";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "fail";
    }

    /**
     * 存储缓存数据,并设置时间
     */
    @ResponseBody
    @RequestMapping(value = "setByTime")//produces = {"application/json;charset=UTF-8"}
    public String setByTime(@RequestParam("key") String key, @RequestBody Object value, @RequestParam("time")long time){
        try {
            Object obj = CacheUtil.linkedHashMapToObject(value, value.getClass());
            redisService.set(key, obj, time);
            return "ok";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "fail";
    }

    /**
     * 获取缓存数据
     */
    @ResponseBody
    @RequestMapping("get")
    public Object get(@RequestParam("key") String key){
        try {
            return redisService.get(key);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 根据 key,判断 value是否存在
     */
    @ResponseBody
    @RequestMapping("exists")
    public String exists(@RequestParam("key") String key){
        boolean exists = redisService.exists(key);
        return String.valueOf(exists);
    }

    /**
     * 删除缓存数据,可删除多个
     */
    @ResponseBody
    @RequestMapping("delete")
    public String delete(@RequestParam("key") String...key){
        redisService.delete(key);
        return "success";
    }
}
